package exemplo.faces;

import java.sql.SQLException;
import java.util.List;

import exemplo.database.ProductDAO;
import exemplo.model.Product;

public class ProductFace {

	private ProductDAO prodDAO;
	private Product selectedProduct;
	private List<Product> products;
	
	public ProductFace(){
		try {
			prodDAO = new ProductDAO();
			System.out.println("My ProductFace has been created!");
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String startAddProduct() {
		selectedProduct = new Product();
		return "gotoAddNewProduct";
	}
	
	public String finishAddProduct() {
		try {
			prodDAO.add(selectedProduct);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		products = null;
		return "gotoListProducts";
	}
	
	public List<Product> getProducts(){
		if (products == null) {
			try {
				products = prodDAO.getAllProducts();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return products;
	}
	
	public String startEditProduct() {
		return "gotoEditProduct";
	}
	
	public String finishEditProduct() {
		try {
			prodDAO.set(selectedProduct);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		products = null;
		return "gotoListProducts";	
	}
	
	public String removeProduct() {
		try {
			prodDAO.delete(selectedProduct);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		products = null;
		return "gotoListProducts";		
	}

	public Product getSelectedProduct() {
		return selectedProduct;
	}

	public void setSelectedProduct(Product selectedProduct) {
		this.selectedProduct = selectedProduct;
	}
}
